#!/usr/bin/env python

# finds *md5* files in the subdirectory tree using command:
#    find ./ -iregex '.*md5.*' -print
# takes each of the files in the returned list, if any, and changes into
#   the parent directory and performs md5sum -c <file>

# deprecated popen2 to subprocess, tested, debugged

# analyze logs and only count occurrences of 
#   "OK" and ""FAILED open or read" and print only other lines

import os
import sys
import subprocess
import tempfile



def printer(outputStream, what):
    outputStream.seek(0)
    print "result (%s):" % what
    analyzer = { "OK": 0,
                 "FAILED open or read": 0,
                 "No such file or directory": 0 }
    for line in outputStream.readlines():
        l = line.strip()
        toPrint = True
        for a in analyzer:
            if l.endswith(a):
                analyzer[a] = analyzer[a] + 1
                toPrint = False
        if toPrint:
            print l

    for a in analyzer:
        if analyzer[a]:
            print "'%s'-ending entries: %s" % (a, analyzer[a])

    

def printer2(outputStream, what):
    outputStream.seek(0)
    print "result (%s):" % what
    okCounter = 0
    failedOpenCounter = 0
    fileNotFoundCounter = 0
    for line in outputStream.readlines():
        l = line.strip()
        if l.endswith("OK"):
            okCounter += 1
        elif l.endswith("FAILED open or read"):
            failedOpenCounter += 1
        elif l.endswith("No such file or directory"):
            fileNotFoundCounter += 1
        else:
            print l
    if okCounter:
        print "'OK'-ending entries: %s" % okCounter
    if failedOpenCounter:
        print "'FAILED open or read'-ending entries: %s" % failedOpenCounter
    if fileNotFoundCounter:
        print ("'No such file or directory'-ending entries: %s" %
                fileNotFoundCounter)




def main():

    print "current directory: '%s'" % os.curdir

    command = "find -iregex .*md5.* -print"
    stdOut = tempfile.TemporaryFile("w+")

    try:
        print "running command: '%s' ... " % command,
        subprocess.check_call(command.split(), stdout = stdOut,
                              close_fds = False)
    except subprocess.CalledProcessError, ex:
        print "error was raised, see output ... ",

    print "finished.\n"

    stdOut.seek(0)

    # store original working directory
    currDir = os.getcwd() 

    for line in stdOut.readlines():
        entry = line.strip()
        print "found entry: '%s'" % entry
        path = os.path.dirname(entry)
        print "changing directory to '%s'" % path
        os.chdir(path)

        fileName = os.path.basename(entry)
        command = "md5sum -c %s" % fileName
        
        stdOutSub = tempfile.TemporaryFile("w+")
        stdErrSub = tempfile.TemporaryFile("w+")
        try:
            print "running command: '%s' ... " % command,
            subprocess.check_call(command.split(), stdout = stdOutSub,
                    stderr = stdErrSub, close_fds = False)
        except subprocess.CalledProcessError, ex:
            print "error was raised, see output ... ",

        print "finished, printing results ..."

        printer(stdOutSub, "stdout")
        printer(stdErrSub, "stderr")

        os.chdir(currDir)
        print "changed to the original working directory '%s'\n\n\n" % currDir


if __name__ == "__main__":
    main()
